package com.gxufl.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.gxufl.entity.Notice;
import com.gxufl.entity.Room;
import com.gxufl.entity.Seat;
import com.gxufl.entity.Ticket;

public class JdbcUtil {

	private static String dbname = "movie";
	private static String username = "root";
	private static String password = "root";

	// 单例模式获取
	public static Connection conn = getConnection();

	/**
	 * 获取连接实例，单例模式
	 */
	private static Connection getConnection() {
		try {

			// 加载mysql驱动程序
			Class.forName("com.mysql.jdbc.Driver");
			// 连接localhost上的mysql,用户名为root,密码为root
			conn = DriverManager.getConnection("jdbc:mysql://localhost/"
					+ dbname + "?useUnicode=true&characterEncoding=utf-8",
					username, password);
			if (!conn.isClosed()) {
				// System.out.println("数据库连接成功！"); // 验证是否连接成功
			} else {
				System.out.println("数据库连接失败！");
			}

			return conn;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 查询list集合
	 */
	public static <T> List<T> query(String sql, Class<T> type) {
		QueryRunner qr = new QueryRunner();
		try {
			return qr.query(JdbcUtil.conn, sql, new BeanListHandler<T>(type));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return new ArrayList<>();
	}

	/**
	 * 查询单个结果
	 */
	public static <T> T queryOne(String sql, Class<T> type) {
		List<T> list = query(sql, type);
		if (list.size() > 1) {
			System.out.println("多于一个结果");
			return null;
		}
		if(list.size() == 1) {
			return list.get(0);
		}
		
		return null;
	}

	/**
	 * 通用保存方法（采用反射实现）
	 */
	public static <T> boolean save(T entity) {

		boolean isOK = true;

		String sql = "";
		Object[] params = null;
		if (entity.getClass().equals(Notice.class)) {
			sql = "insert into movie_notice(name,content,showdate,priority) values(?,?,?,?)";
			Notice notice = (Notice) entity;
			params = new Object[] { notice.name, notice.content,
					notice.showdate, notice.priority };
		} else if (entity.getClass().equals(Room.class)) {
			sql = "insert into movie_room(name,num) values(?,?)";
			Room room = (Room) entity;
			params = new Object[] { room.name, room.num };
		} else if (entity.getClass().equals(Seat.class)) {
			sql = "insert into movie_seat(roomid,roomname,code,isuse) values(?,?,?,?)";
			Seat seat = (Seat) entity;
			params = new Object[] { seat.roomid, seat.roomname, seat.code,
					seat.isuse };
		} else if (entity.getClass().equals(Ticket.class)) {
			sql = "insert into movie_ticket(noticeid,noticename,roomid,roomname,usertel,seatcode,price) values(?,?,?,?,?,?,?)";
			Ticket ticket = (Ticket) entity;
			params = new Object[] { ticket.noticeid, ticket.noticename,
					ticket.roomid, ticket.roomname, ticket.usertel,
					ticket.seatcode, ticket.price };
		}
		// TODO: 实现存数据库逻辑

		QueryRunner qr = new QueryRunner();
		try {
			qr.update(conn, sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
			isOK = false;
		}

		return isOK;
	}

	public static <T> boolean save2(T entity) {
		boolean isOK = true;
		try {

			String tablename = entity.getClass().getName();
			Field[] fields = entity.getClass().getDeclaredFields();

			List<String> names = new ArrayList<>();
			List<Object> params = new ArrayList<>();

			for (int i = 0, ii = fields.length; i < ii; i++) {
				Field f = fields[i];
				f.setAccessible(true);
				String name = f.getName();
				if (name.equals("id")) {
					continue;
				}
				names.add(name);
				params.add(f.get(entity));
			}

			String sql = "insert info " + tablename;

			QueryRunner qr = new QueryRunner();
			qr.update(conn, sql, params);
		} catch (Exception e) {

			isOK = false;
		}

		return false;
	}

	/**
	 * 通用删除方法
	 * 
	 * @param id
	 *            数据库表关键字
	 */
	public static boolean delete(Integer id, String whatTable) {

		boolean isOK = true;
		QueryRunner qr = new QueryRunner();
		// TODO:(完成) 实现删除数据库逻辑

		String sql = "delete from movie_" + whatTable + " where id = ?";
		try {
			qr.update(conn, sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
			isOK = false;
		}

		return isOK;
	}

	/**
	 * 通用删除方法
	 * 
	 * @param id
	 *            数据库表关键字
	 */
	public static <T> boolean delete(Integer id, Class<T> clazz) {
		String entityName = clazz.getSimpleName().toLowerCase();
		return delete(id, entityName);
	}

}
